// @algorithm @lc id=100329 lang=javascript
// @title zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
// @test([5,7,7,8,8,10],8)=2
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var search = function (nums, target) {
  const binarySearch = (isLower) => {
    let l = 0;
    let r = nums.length - 1;
    let mid;
    while (l <= r) {
      mid = l + ((r - l) >> 1);
      if (nums[mid] > target || (isLower && nums[mid] >= target)) {
        r = mid - 1;
      } else {
        l = mid + 1;
      }
    }
    return l;
  };

  let ans = 0;
  const l = binarySearch(true);
  const r = binarySearch(false) - 1;

  if (l <= r && r <= nums.length && nums[l] === target && nums[r] === target) {
    ans = r - l + 1;
  }

  return ans;
};
